import { DemoBlock } from '@/components/demos-util';
import { type DetailResult } from '@/pages/types/type';
import { checkAuthorize } from '@/utils/authorize';
import { Content, Page } from '@alita/flow';
import { setPageNavBar, useLocation, useNavigate } from 'alita';
import {
  Button,
  Card,
  DotLoading,
  Form,
  Input,
  List,
  NavBar,
  Space,
  Tag,
  Toast,
} from 'antd-mobile';
import { useEffect, useState } from 'react';

import { type Device } from '@/pages/types/type';
import { getRequestInit, postRequestInit, urlPrefix } from '@/utils/http';
import { useModel } from 'alita';
import { AntOutline, RightOutline } from 'antd-mobile-icons';
import styles from './index.less';
import {type DeviceNeedRegister} from '@/pages/types/type';
const numberFormator = new Intl.NumberFormat();

export default () => {
  const navigate = useNavigate();
  const location = useLocation();
  //   const [searchParams, setSearchParams] = useSearchParams();
  const [tokening, setTokening] = useState<boolean>(true);
  const [tokenFail, setTokenFail] = useState<string | undefined>(undefined);
  const [authOK, setAuthOK] = useState<boolean>(false);
  const [loadFails, setLoadFails] = useState<string[]>([]);
  const [loadOK, setLoadOK] = useState<string | undefined>(undefined);
  const [loadingTimes, setLoadingTimes] = useState<number>(0);

  // 提交时状态控制
  const [ing, setIng] = useState<boolean>();
  const [fail, setFail] = useState<string>();
  const [success, setSuccess] = useState<string>();
  const [needs, setNeeds] = useState<DeviceNeedRegister[]>([]);
    
  type FieldModal = {
    deviceSerialNumber: string;
    meta: string;
  };
  const [form] = Form.useForm<FieldModal>();

  const model = useModel('useAuthModel');
  useEffect(() => {
    setPageNavBar({
      pagePath: location.pathname,
      navBar: {
        hideNavBar: true,
        pageTitle: `待注册设备列表`,
        pageBackground: '#eee',
      },
    });
    checkAuthorize(
      (x) => setTokening(x),
      (y) => {
        console.log(`token检查完成，是否通过授权：${y}`);
        setAuthOK(y);
      },
      (z) => setTokenFail(z),
      model,
    );
  }, []);

  function load() {
    if (authOK) {
      let times = 1;
      // 加载全部申请注册的设备
      fetch(`${urlPrefix}/api/rayplatform/device-need-register/get-all-device-need-register`, getRequestInit())
        .then(async (rsp: Response) => {
          if (rsp.ok) {
            await rsp
              .json()
              .then(({ data, code, msg }: DetailResult<DeviceNeedRegister[]>) => {
                Toast.show(msg);
                if (code === 0) {
                  if (data) {
                    setNeeds(data!);
                  }
                  setLoadOK(msg);
                } else {
                  setLoadFails([...loadFails, msg]);
                }
              })
              .catch((reason) => {
                setLoadFails([...loadFails, reason]);
              });
          }
        })
        .catch((reason: any) => {
          console.error(reason);
          setLoadFails([...loadFails, `加载待注释设备：${reason}`]);
        })
        .finally(() => {
          setLoadingTimes(--times);
        });
    } // end if authOK
  }
  useEffect(load, [authOK]);

  const onFinish = (values: FieldModal) => {
    // Dialog.alert({
    //   content: <pre>{JSON.stringify(values, null, 2)}</pre>,
    // });
    // return;
    const url = '/api/rayplatform/device-need-register/boot';
    const requestInit: RequestInit = postRequestInit({
      ...values,
      version: 'OK',
    });
    let response: Promise<Response> = fetch(`${urlPrefix}${url}`, requestInit);
    response
      .then(async (rsp: Response) => {
        if (rsp.ok) {
          rsp
            .json()
            .then(async (x: DetailResult<string>) => {
              const { data, code, msg } = x;
              if (code === 0) {
                //setSuccess(msg);
                if (data!.length > 5) {
                  Toast.show(data!);
                } else {
                  Toast.show(msg);
                }
              } else {
                setFail(msg);
              }
            })
            .catch((reason) => {
              setFail(reason);
              console.error(`${url} catch in 最内层!`);
            })
            .finally(() => {
              console.log(`finally in 最内层:${url}`);
            });
        } else {
          setFail(`rsp not OK![${url}]`);
          console.log(`!!! rsp not ok! [${url}]`);
        }
      })
      .catch((reason: any) => {
        console.error(reason);
        setFail(`发生错误：${reason}[${url}]`);
        console.error(`${url} catch in 最外层`);
      })
      .finally(() => {
        setIng(false);
        console.log(`finally in 最外层:${url}`);
      });
  };

  if (tokening) {
    return (
      <div style={{ color: '#00b578' }}>
        <DotLoading color="currentColor" />
        <span>正在授权...</span>
      </div>
    );
  }

  if (loadingTimes > 0) {
    return (
      <div style={{ color: '#00b578' }}>
        <DotLoading color="currentColor" />
        <span>正在载入,剩余{loadingTimes}个请求...</span>
      </div>
    );
  }

  return (
    <Page>
      <Content>
        <DemoBlock padding={8}>
          <NavBar
            left={
              <Button
                color="primary"
                size="mini"
                shape="rounded"
                onClick={() => navigate('/')}
              >
                首
              </Button>
            }
            // 未定义导航栏右侧内容！
            onBack={() => navigate(-1)}
          >
            待注册设备列表
          </NavBar>
        </DemoBlock>

        <Card
          title={
            <div style={{ fontWeight: 'normal' }}>
              <AntOutline style={{ marginRight: '4px', color: '#1677ff' }} />
              待注册设备列表
            </div>
          }
          extra={<RightOutline />}
          // onBodyClick={onBodyClick}
          // onHeaderClick={onHeaderClick}
          style={{ borderRadius: '16px', margin: '10px' }}
        >
          <div className={styles.content}>
            <List>
                {needs.map(({ id ,deviceSerialNumber,meta,updatedAt })=><List.Item
                onClick={()=> navigate(`/device/do-register?id=${id}`)}
                 key={id}
                description={<>
                元数据：{meta}
                </>}
                >
                    {deviceSerialNumber}
                </List.Item>)}
            </List>
          </div>
        </Card>
      </Content>
    </Page>
  );
};